package com.iqik.sc.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    private static List<String> blackList = new ArrayList<>();

    static {
        blackList.add("0:0:0:0:0:0:0:1");
        blackList.add("127.0.0.1");
    }

    /**
     * 过滤器核心方法，
     * @param exchange 封装request和response对象的上下文
     * @param chain 网关过滤器链（包含全局过滤器和单路由过滤器
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从request和response获取客户端ip，是否在黑名单中，在就拒绝，否则通过
        // 获取request和response对象
        System.out.println("过滤器执行");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();
        System.out.println(clientIp);
        if (blackList.contains(clientIp)) {
            // 决绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 设置状态码
            String data = "Request be denied";
            response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(response.bufferFactory().wrap(data.getBytes())));
        }
        // 合法请求

        return chain.filter(exchange);
    }

    /**
     * 返回值表示当前过滤器的顺序（优先级，数值越小，优先级越高）
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
